<template>
  <el-dialog :close-on-click-modal="false" :title="$tt('label_batch_measure')" :visible.sync="visible"
    custom-class="dialog_big" destroy-on-close>
    <div v-loading="loading">
      <el-form :model="form" ref="form" label-position="top">
        <el-form-item :label="$tt('label_file_upload')">

          <button_select_file @input="selectFile" type="primary">
            {{ $tt('label_import_excel') }}
            <i class="el-icon-upload2 el-icon--right"></i>
          </button_select_file>
          <el-button @click="downloadXlsx" size="mini" type="primary">{{ $tt('label_download_import_template') }}<i
              class="el-icon-download el-icon--right"></i></el-button>
        </el-form-item>
        <el-form-item prop="tableList" :label="$tt('label_box_list')">
          <ex_super_table ref="table" v-bind="tableBaseOption" :data="form.tableList" height="600">
          </ex_super_table>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog_footer">
        <el-button @click="visible = false">{{ $tt('label_cancel') }}</el-button>
        <el-button type="primary" @click="submit">{{ $tt('label_submit') }}</el-button>
      </span>
    </div>

  </el-dialog>
</template>

<script>
import volume_input from '@/component/wms/volume_input.vue';
import select_file_temp from '@/component/base/select_file_temp'
// import xlsx from '@/asset/xlsx.full.min.js'
import ExcelJS from '@/asset/exceljs.bare.min.js'

export default {
  name: 'transfer_receive_measure',
  components: { volume_input, select_file_temp, },
  data() {
    return {

      visible: false,
      loading: false,
      form: {
        tableList: [],
      },
      tableBaseOption: {
        attrs: {},
        model: [
          { key: 'packageNo', label: 'label_package_code', 'min-width': 160, },
          // {
          //   key: 'inboundOrderCodeList', label: 'label_inbound_code', 'min-width': 160,
          //   render: (h, { row }) => {
          //     if (row.inboundOrderCodeList) {
          //       return (
          //         row.inboundOrderCodeList.map(item => {
          //           return <div class=''>{item}</div>
          //         })
          //       )
          //     }
          //   }
          // },
          {
            key: 'weight', label: 'label_weight', 'width': 120, 'label-class-name': 'table_header_require',
            render: (h, { column, row, index }) => {
              return (
                <el-form-item
                  prop={`tableList.${index}.${column.property}`}
                  rules={this.formRules[column.property]}
                >
                  <ex_super_input
                    value={row[column.property]}
                    onInput={value => {
                      this.$set(row, column.property, value)
                    }}
                    placeholder={column.label}
                    append="kg"
                  >
                  </ex_super_input>
                </el-form-item>
              );
            }
          },
          {
            key: 'length', label: 'label_length', 'width': 120, 'label-class-name': 'table_header_require',
            render: (h, { column, row, index }) => {
              return (
                <el-form-item
                  prop={`tableList.${index}.${column.property}`}
                  rules={this.formRules['dimen']}
                >
                  <ex_super_input
                    value={row[column.property]}
                    onInput={value => {
                      this.$set(row, column.property, value)
                    }}
                    placeholder={column.label}
                    append="cm"
                  >
                  </ex_super_input>
                </el-form-item>
              );
            }
          },
          {
            key: 'width', label: 'label_width', 'width': 120, 'label-class-name': 'table_header_require',
            render: (h, { column, row, index }) => {
              return (
                <el-form-item
                  prop={`tableList.${index}.${column.property}`}
                  rules={this.formRules['dimen']}
                >
                  <ex_super_input
                    value={row[column.property]}
                    onInput={value => {
                      this.$set(row, column.property, value)
                    }}
                    placeholder={column.label}
                    append="cm"
                  />
                </el-form-item>
              );
            }
          },
          {
            key: 'height', label: 'label_height', 'width': 120, 'label-class-name': 'table_header_require',
            render: (h, { column, row, index }) => {
              return (
                <el-form-item
                  prop={`tableList.${index}.${column.property}`}
                  rules={this.formRules['dimen']}
                >
                  <ex_super_input
                    value={row[column.property]}
                    onInput={value => {
                      this.$set(row, column.property, value)
                    }}
                    placeholder={column.label}
                    append="cm"
                  />

                </el-form-item>
              );
            }
          },


        ],
      },
      formRules: {
        weight: {
          required: true, trigger: 'change',
          validator: (r, v, cb) => {
            if (!this.$reg.DigitNumber(v, 3, 9)) {
              return cb(this.$tt("tip_only_digit_int_length", { digit: 3, int: 9 }))
            }
            cb()
          }
        },
        dimen: {
          required: true, trigger: 'change',
          validator: (r, v, cb) => {
            if (!this.$reg.DigitNumber(v, 2, 9)) {
              return cb(this.$tt("tip_only_digit_int_length", { digit: 2, int: 9 }))
            }
            cb()
          }
        },
      },
      xlsxStructure: {
        packageNo: { key: 'packageNo', label: this.$tt('label_package_code'), index: 1, },
        weight: { key: 'weight', label: this.$addUnit(this.$tt('label_weight'), '(kg)'), index: 2, },
        length: { key: 'length', label: this.$addUnit(this.$tt('label_length'), '(cm)'), index: 3, },
        width: { key: 'width', label: this.$addUnit(this.$tt('label_width'), '(cm)'), index: 4, },
        height: { key: 'height', label: this.$addUnit(this.$tt('label_height'), '(cm)'), index: 5, },
      }
    }
  },
  props: {
  },
  methods: {
    selectFile(e) {

      let reader = new FileReader();
      const importList = _.cloneDeep(this.form.tableList)
      const xlsxStructure = this.xlsxStructure
      reader.onload = (e) => {
        const data = e.target.result
        new ExcelJS.Workbook().xlsx.load(data).then(workbook => {
          const worksheet = workbook.getWorksheet(1)
          let sumImportCount = 0
          let successMateImportCount = 0
          let insertList = []
          worksheet.eachRow((row, rowNumber) => {
            if (rowNumber == 1) return
            sumImportCount++
            const packageNo = row.getCell(xlsxStructure['packageNo'].index).text
            const item = _.find(importList,
              indata => indata.packageNo == packageNo)
            if (item) {
              successMateImportCount++
              item.weight = row.getCell(xlsxStructure['weight'].index).text
              item.length = row.getCell(xlsxStructure['length'].index).text
              item.width = row.getCell(xlsxStructure['width'].index).text
              item.height = row.getCell(xlsxStructure['height'].index).text
            } else if (packageNo) {
              const insert = {}
              _.forOwn(xlsxStructure, (v, k) => {
                insert[v.key] = row.getCell(xlsxStructure[v.key].index).text
              })
              insertList.push(insert)
            }
          });
          importList.push(...insertList)
          this.$alert(
            this.$tt('tip_sum_import_count_success_mate_count', { sum: sumImportCount, success: successMateImportCount }),
            this.$tt('label_tip'),);
          this.form.tableList = importList
        })
      };
      reader.readAsArrayBuffer(e[0]);
    },

    downloadXlsx() {
      // if (_.isEmpty(this.form.tableList)) {
      //   this.$alert(this.$tt('tip_no_has_can_operate_data'), this.$tt("label_tip"), {
      //     type: 'warning'
      //   }).then(() => {

      //   }).catch(() => {
      //   });
      //   return
      // }

      const wb = new ExcelJS.Workbook()
      const worksheet = wb.addWorksheet(this.$tt('label_pack_measure_import_template'))

      const sts = _.sortBy(Object.values(this.xlsxStructure), 'index')
      worksheet.addRow(sts.map(it => it.label));
      this.form.tableList.forEach(it => {
        worksheet.addRow(sts.map(s => it[s.key] ? it[s.key] : null));
      })


      wb.xlsx.writeBuffer().then(buffer => {
        this.$downloadBuffer({
          buffer,
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
          filename: `${this.$tt('label_pack_measure_import_template')}${new Date().getTime()}.xlsx`,
        })
      })
    },

    cellClassName({ row, column, rowIndex, columnIndex }) {
      if (['orderInfo',].includes(column.property)) {
        return "revert_cell_border"
      }
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (['receivingCode', 'customerCode', 'orderInfo', 'orderSku',].includes(column.property)) {
        return { rowspan: row.rowspanOrder, colspan: 1 }
      }

    },
    show({ tableList }) {
      this.loading = false
      this.form.tableList = _.cloneDeep(tableList)
      this.visible = true

    },


    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {

          this.$ajax({
            url: "/wms-api/inbound/WmsInboundTransitPackagingRpc/measureBatch.json",
            method: 'post',
            type: 'json',
            loading: this.$tt('tip_submiting'),
            data: { measureList: this.form.tableList },
            success: (res) => {
              this.$message.success(this.$tt("tip_submit_success"))
              this.$emit("submitSuccess")
              this.visible = false
            },
          })
        } else {
          this.$message.error(this.$t('form_validate_error'))
          return false;
        }
      });
      return
      // if (this.tableList.some(it => !it.temporaryAreaId)) {
      //   return this.$message.error(this.$tt("tip_please_select_warehouse_area"))
      // }




    }

  }
}
</script>
